package cn.orange.ch08_backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * LC40.组合总和II
 */
public class LC40 {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        LinkedList<Integer> trace = new LinkedList<>();
        Arrays.sort(candidates);
        backtracking(0, candidates, target, trace, ans);
        return ans;
    }

    private void backtracking(int start, int[] candidates, int target, LinkedList<Integer> trace, List<List<Integer>> ans) {
        if (target == 0) {
            ans.add(new ArrayList<>(trace));
            return;
        }
        if (target < 0) return;
        for (int i = start; i < candidates.length; i++) {
            int candidate = candidates[i];
            if (candidate > target) continue;
            if (i > start && candidates[i] == candidates[i - 1]) continue;
            trace.add(candidate);
            backtracking(i + 1, candidates, target - candidate, trace, ans);
            trace.removeLast();
        }
    }

    public static void main(String[] args) {
        LC40 alg = new LC40();
        System.out.println(alg.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8));
        System.out.println(alg.combinationSum2(new int[]{2, 5, 2, 1, 2}, 5));
    }
}
